<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="Form" :inline="true" label-width="90px">
      <el-form-item label="日期：" prop="dateTtime">
        <el-date-picker
          v-model="dateTtime"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          :editable="false"
          type="date"
          placeholder="请选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          style="margin-left: 10px"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item
        v-for="(item, index) in breadcrumbList"
        :key="index"
        @click.native="clickBreadcrumb(item)"
        ><span
          style="
            cursor: pointer;
            font-weight: bold;
            margin-left: 10px;
            font-size: 18px;
          "
          >{{ item.name }}</span
        ></el-breadcrumb-item
      >
    </el-breadcrumb>
    <div class="charts">
      <div ref="myChartdom1" class="chartdom1"></div>
      <div>
        <p style="font-weight: 600">数据来源：手环</p>
        <div ref="myChartdom2" class="chartdom2"></div>
      </div>
    </div>
    <sportIndex
      :showDialog.sync="showDialog"
      :schoolCode="schoolCode"
      :classId="parseInt(classId)"
      :infoValue="infoValue"
    ></sportIndex>
  </div>
</template>
<script>
import moment from "moment";
import sportIndex from "@/components/sports/index.vue";
import {
  areaRecord,
  areaRecordavg,
  schoolRecordavg,
  classRecordavg,
  configKey,
} from "@/api/qu/qyyeydzx.js";
import { formatDateOnly } from "@/utils";
import { formatTimeDate } from "@/utils";

export default {
  name: "qyyeydzx",
  components: {
    sportIndex,
  },
  data() {
    return {
      dateTtime: new Date(),
      queryParams: {},
      showDialog: false,
      sportsList: [
        { name: "充足", value: 2 },
        { name: "达标", value: 2 },
        { name: "不足", value: 2 },
        { name: "未入园", value: 5 },
      ],
      schoolList: [
        { name: "幼儿园1", value: "3" },
        { name: "幼儿园2", value: "3" },
        { name: "幼儿园3", value: "3" },
        { name: "幼儿园4", value: "3" },
      ],
      breadcrumbList: [
        { name: "全区", value: "1" },
        // {name:'幼儿园',value:'2'},
        // {name:'年级',value:'3'},
      ],
      bread: {
        name: "",
        value: "",
      },
      schoolTitle: "各园平均运动量情况",
      title: "全区幼儿运动情况",
      myCharts1: null,
      myCharts2: null,
      schoolCode: "",
      classId: "",
      sportTitle: "平均运动量",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      previousDate: "",
      infoValue: [],
      sportDate: [],
    };
  },
  created() {
    // 获取当前日期
    const currentDate = new Date();
    // 获取前一天的日期
    this.previousDate = new Date(currentDate);
    this.previousDate.setDate(currentDate.getDate() - 1);
    this.dateTtime = formatDateOnly(this.previousDate);
  },
  mounted() {
    this.myCharts1 = this.$echarts.init(this.$refs.myChartdom1);
    this.myCharts2 = this.$echarts.init(this.$refs.myChartdom2);
    this.init();
    window.addEventListener("resize", this.monitorResize);
  },
  methods: {
    init() {
      this.getAreaRecord();
      this.getareaRecordavg();
    },
    //监听添加面包屑
    addBread(bread) {
      const index = this.breadcrumbList.findIndex(
        (item) => item.name === bread.name
      );
      if (index > -1) {
        const index = this.breadcrumbList.findIndex(
          (item) => item.name === bread.name
        );
        this.breadcrumbList = this.breadcrumbList.slice(0, index + 1);
      } else {
        this.breadcrumbList.push(bread);
      }
    },
    //全区幼儿运动
    async getAreaRecord() {
      try {
        const obj = {
          date: moment(this.dateTtime).format("YYYY-MM-DD"),
          schoolCode: this.schoolCode,
          classId: this.classId,
        };
        const { data } = await areaRecord(obj);
        this.sportsList = data.map((item) => {
          return {
            name: item.type,
            value: item.personNum,
            percent: item.percent,
          };
        });
        this.myChartsFn1();
      } catch (error) {
        console.log(error);
      }
    },
    //各园平均运动量
    async getareaRecordavg() {
      try {
        const obj = {
          date: moment(this.dateTtime).format("YYYY-MM-DD"),
        };
        const { data } = await areaRecordavg(obj);
        if (data.length !== 0) {
          this.schoolList = data.map((item) => {
            return {
              name: item.schoolName,
              value: item.stepAvg,
              code: item.schoolCode,
            };
          });
        } else {
          this.schoolList = [
            {
              name: "",
              code: "0",
              value: 0,
            },
          ];
        }

        this.myChartsFn2();
      } catch (error) {
        console.log(error);
      }
    },
    //班级层面平均运动量
    async getschoolRecordavg() {
      this.sportDate = []
      try {
        const obj = {
          date: moment(this.dateTtime).format("YYYY-MM-DD"),
          schoolCode: this.schoolCode,
        };
        const { data } = await schoolRecordavg(obj);
        let currentDate = []; // 当前日期
        let newDate = []; // 前一天日期
        const a = new Date(this.dateTtime);
        const time = a.getTime() - 86400000 * 1;
        const dateDay = formatDateOnly(time);

        data.forEach((item) => {
          if (item.createDate == dateDay) {
            const obj = {
              name: item.className,
              value: item.stepAvg,
              code: item.classId,
            };
            currentDate.push(obj);
          } else if (item.createDate == this.dateTtime) {
            const obj = {
              name: item.className,
              value: item.stepAvg,
              code: item.classId,
            };
            newDate.push(obj);
          }
        });

        this.sportDate = newDate;
        this.schoolList = currentDate
        this.myChartsFn2();
      } catch (error) {
        console.log(error);
      }
    },
    //幼儿运动情况
    async classRecordRecordavg() {
      try {
        this.sportDate = []
        const obj = {
          date: moment(this.dateTtime).format("YYYY-MM-DD"),
          classId: this.classId,
        };
        const { data } = await classRecordavg(obj);

        this.schoolList = data.map((item) => {
          return {
            name: item.stuName,
            value: item.stepAvg,
            code: item.stuId,
            sex: item.sex,
            level: item.level,
          };
        });
        this.myChartsFn2();
      } catch (error) {
        console.log(error);
      }
    },
    //点击面包屑
    clickBreadcrumb(bread) {
      this.sportDate = []
      // if(bread.code ==='全网') return
      // this.radio='01'
      const index = this.breadcrumbList.findIndex(
        (item) => item.name === bread.name
      );
      this.breadcrumbList = this.breadcrumbList.slice(0, index + 1);
      if (bread.name == "全区") {
        this.bread = {
          name: "",
          value: "",
        };
        this.schoolTitle = "各园平均运动量";
        this.title = "全区幼儿运动情况";
        this.schoolCode = "";
        this.classId = "";
        this.init();
      } else if (bread.name.includes("幼儿园")) {
        this.bread = {
          name: bread.name,
          value: bread.value,
        };
        this.schoolTitle = bread.name + "平均运动量";
        this.title = bread.name + "幼儿运动情况";
        this.classId = "";
        this.getschoolRecordavg();
        this.getAreaRecord();
      } else if (bread.name.includes("班")) {
        this.schoolTitle = bread.name + "各幼儿运动量";
        this.title = bread.name + "幼儿运动情况";
        this.getAreaRecord();
        this.classRecordRecordavg();
      } else {
        this.bread = {
          name: "",
          value: "",
        };
        this.classId = "";
        this.schoolCode = "";
        this.schoolTitle = "各园平均运动量";
        this.title = "全区幼儿运动情况";
        this.init();
      }
    },
    //全区幼儿运动情况
    myChartsFn1() {
      const option = {
        title: [
          {
            text: this.title,
            left: "left",
            subtext: "单位：人",
            subtextStyle: {
              color: "#000",
            },
          },
        ],
        legend: {
          data: ["充足", "达标", "不足", "未入园"],
          right: 20,
          top: 30,
          y: "top",
          orient: "vertical",
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: { show: true, title: "下载" },
          },
        },
        tooltip: {
          trigger: "item",
          //  formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        series: [
          {
            name: "",
            type: "pie",
            radius: "48%",
            center: ["40%", "50%"],
            data: this.sportsList,
            label: {
              position: "outer",
              alignTo: "none",
              bleedMargin: 5,
            },
            left: 0,
            //  right: '45%',
            top: 0,
            bottom: 0,
          },
        ],
      };
      // 使用刚指定的配置项和数据显示图表
      this.myCharts1.setOption(option, true);
      window.addEventListener("resize", this.monitorResize);
    },
    //柱状图
    myChartsFn2() {
      this.myCharts2.off("click"); //解绑---请求只发一次
      const option = {
        // backgroud:'#333',
        title: {
          text: this.schoolTitle,
          //  subtext: 'Fake Data',
          left: "left",
        },
        dataZoom: {
          bottom: 0,
          show: 8 / this.schoolList.length < 1,
          // show:true,
          type: "slider",
          zoomLock: true,
          brushSelect: false,
          height: 8,
          // backgroundColor:'#000000',
          handleSize: "0",
          // moveHandleSize:1,
          // moveHandleStyle:{
          //   borderType:'dotted'
          // },
          sow: true,
          xAxisIndex: [0],
          start: 0,
          end: (8 / this.schoolList.length) * 100,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: { show: true, title: "下载" },
          },
        },
        legend: {},
        grid: {
          left: "4%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            axisLabel: {
              //x轴文字的配置
              show: true,
              interval: 0, //使x轴文字显示全
            },
            // data:this.echartList.map((item) => item.name)
            data: this.schoolList.map((item) => item.name),
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "单位：步数",
          },
        ],
        color: ["#2f89cf", "#27d08a"],
        series: [
          {
            name: this.sportTitle,
            type: "bar",
            // stack: 'Ad',
            emphasis: {
              focus: "series",
            },
            barWidth: "30%",
            label: {
              show: true,
              position: "inside",
              fontSize: 15,
            },
            // data: this.echartList.map((item) => item.value),
            data: this.schoolList,
          },
          {
            name: '前一天运动量',
            type: "bar",
            // stack: 'Ad',
            emphasis: {
              focus: "series",
            },
            barWidth: "30%",
            label: {
              show: true,
              position: "inside",
              fontSize: 15,
            },
            // data: this.echartList.map((item) => item.value),
            data: this.sportDate,
            itemStyle: function(params) {
            if (params.dataIndex === 1) {   // 判断当前柱子的索引值是否等于1
                return {
                    opacity: 0   // 将不透明度设置为0，表示完全隐藏该柱子
                };
            } else {
                return {};   // 返回空对象，保持默认样式
            }
        },
          },

        ],
      };
      this.myCharts2.on("click", (params) => {
        if (params.componentType === "series") {
          if (params.name.includes("幼儿园")) {
            this.schoolCode = params.data.code;
            this.bread = {
              name: params.name,
              value: this.schoolCode,
            };
            this.addBread(this.bread);
            this.title = params.name + "幼儿运动情况";
            this.schoolTitle = params.name + "各班平均运动量";
            this.getAreaRecord();
            this.getschoolRecordavg();
          } else if (params.name.includes("班")) {
            this.classId = params.data.code;
            this.bread = {
              name: params.name,
              value: this.classId,
            };
            this.addBread(this.bread);
            this.sportTitle = "运动量";
            this.title = params.name + "幼儿运动情况";
            this.schoolTitle = params.name + "各幼儿运动量";
            this.getAreaRecord();
            this.classRecordRecordavg();
          } else {
            this.infoValue = [
              {
                name: params.data.name,
                sex: params.data.sex == 1 ? "女" : "男",
                level:
                  params.data.level == 1
                    ? "不足"
                    : params.data.level == 2
                    ? "达标"
                    : "充足",
                value: params.data.value,
              },
            ];
            this.showDialog = true;
          }
        }
      });
      // 使用刚指定的配置项和数据显示图表
      this.myCharts2.setOption(option, true);
      window.addEventListener("resize", this.monitorResize);
    },
    handleQuery() {
      if (this.bread.name == "") {
        this.bread = {
          name: "",
          value: "",
        };
        this.schoolTitle = "各园平均运动量";
        this.title = "全区幼儿运动情况";
        this.schoolCode = "";
        this.classId = "";
        this.init();
      } else if (this.bread.name.includes("幼儿园")) {
        this.bread = {
          name: bread.name,
          value: bread.value,
        };
        this.schoolTitle = this.bread.name + "平均运动量";
        this.title = this.bread.name + "幼儿运动情况";
        this.classId = "";
        this.getschoolRecordavg();
        this.getAreaRecord();
      } else if (this.bread.name.includes("班")) {
        this.schoolTitle = this.bread.name + "各幼儿运动量";
        this.title = this.bread.name + "幼儿运动情况";
        this.getAreaRecord();
        this.classRecordRecordavg();
      } else {
        this.bread = {
          name: "",
          value: "",
        };
        this.classId = "";
        this.schoolCode = "";
        this.schoolTitle = "各园平均运动量";
        this.title = "全区幼儿运动情况";
        this.init();
      }
    },
    resetQuery() {
      this.schoolTitle = "各园平均运动量";
      this.title = "全区幼儿运动情况";
      this.dateTtime = formatDateOnly(this.previousDate);
      (this.breadcrumbList = [{ name: "全区", value: "1" }]),
        (this.classId = "");
      this.schoolCode = "";
      (this.bread = {
        name: "",
        value: "",
      }),
        this.init();
    },
    //地图监听窗口缩放事件
    monitorResize() {
      this.myCharts1.resize();
      this.myCharts2.resize();
    },
  },
};
</script>
<style lang="scss" scoped>
.charts {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 100%;
  height: 840px;
  margin-top: 20px;

  .chartdom1 {
    width: 38%;
    height: 60%;
  }

  & > div {
    width: 56%;
    height: 100%;
    position: relative;

    p {
      position: absolute;
      right: 0%;
      top: -5%;
    }
  }

  .chartdom2 {
    width: 100%;
    height: 60%;
  }
}
</style>

